#include <boost/bind.hpp>
#include <boost/asio.hpp>
#include <iostream>
#include <sstream>
#include <iomanip>
#include <ctime>
#include "session.h"

Session::Session(boost::asio::io_service& _ioService)
: socket_(_ioService) {
    memset(msg_, 0, sizeof(msg_));
}

Session::~Session(void) {
}

void Session::start(void) {
    // 告诉链接成功的客户端，你想要的信息。
	char msg[256] = "Connect Succeed! I will feedback the measured distance and speed to you.";
	boost::asio::async_write(socket_, boost::asio::buffer(msg, strlen(msg)),
		boost::bind(&Session::write_handler, shared_from_this(),
		boost::asio::placeholders::error));
}

boost::asio::ip::tcp::socket& Session::socket(void) {
    return socket_;
}

void Session::send_data() {
    // 获取当前时间
    auto now = std::time(nullptr);
    std::tm now_tm = *std::localtime(&now);

    // 构造要发送的数据
    std::stringstream ss;
    ss << std::put_time(&now_tm, "%Y-%m-%d %H:%M:%S") << "," 
       << measurement << "," 
       << time_diff << "," 
       << speed;

    std::string data = ss.str();

    // 异步发送数据
    boost::asio::async_write(socket_, boost::asio::buffer(data),
        boost::bind(&Session::write_handler, shared_from_this(),
        boost::asio::placeholders::error));
}

void Session::write_handler(const boost::system::error_code& _error) {
    if (_error) {
        std::cerr << "Error during write: " << _error.message() << std::endl;
        return;
    }
    // 可以在此处添加更多操作，例如关闭连接或继续发送数据
}

